﻿using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace Best.SmartCms.Utility.JsonFormater
{
    /// <inheritdoc />
    public class CustomizeDateTimeConverter : DateTimeConverterBase
    {

        /// <inheritdoc />
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            try
            {
                if (value == null)
                {
                    writer.WriteValue("");
                }
                else
                {
                    writer.WriteValue(((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss"));
                }
            }
            catch (Exception)
            {
                writer.WriteValue("");
            }
        }

        /// <inheritdoc />
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
            JsonSerializer serializer)
        {
            if (!DateTime.TryParse(reader.Value?.ToString(), out var value))
            {
                return null;
            }

            return value;
        }


        /// <inheritdoc />
        public override bool CanConvert(Type objectType)
        {
            return true;
        }
    }
}